package weibo

import (
	"encoding/base64"
	"io/ioutil"
	"net/http"
	"net/url"

	"strings"

	"github.com/bitly/go-simplejson"
)

//百度AI开放平台基础地址
const BaseUrl = "https://aip.baidubce.com"

//通用文字识别
const BaseValidateUrl = BaseUrl + "/rest/2.0/ocr/v1/general_basic"

type ValidateClient struct {
	ApiKey    string
	SecretKey string

	access_token string
	expires_in   int
}

var valClient *ValidateClient

func (vc *ValidateClient) GetAccessToken() {
	data := url.Values{}
	data.Set("grant_type", "client_credentials")
	data.Set("client_id", vc.ApiKey)        //应用的API Key
	data.Set("client_secret", vc.SecretKey) //应用的Secret Key

	resp, _ := http.PostForm(BaseUrl+"/oauth/2.0/token", data)
	defer resp.Body.Close()

	b, _ := ioutil.ReadAll(resp.Body)
	js, _ := simplejson.NewJson(b)
	var err error
	vc.access_token, err = js.Get("access_token").String()
	if err != nil {
		Fatal(string(b))
	}
	vc.expires_in, _ = js.Get("expires_in").Int() //秒为单位，一般为1个月

	Info("access_token", vc.access_token, "expires_in", vc.expires_in)
	return
}

func (vc *ValidateClient) getWord(filePath string) (log_id int, word string) {
	content, err := ioutil.ReadFile(filePath)
	if err != nil {
		Fatal(err)
	}

	postData := url.Values{}
	postData.Set("image", base64.StdEncoding.EncodeToString(content)) //base64编码
	postData.Set("language_type", "ENG")
	postData.Set("detect_direction", "true")

	resp, _ := http.PostForm(BaseValidateUrl+"?access_token="+vc.access_token, postData)
	defer resp.Body.Close()

	b, _ := ioutil.ReadAll(resp.Body)
	Info(string(b))
	js, _ := simplejson.NewJson(b)
	log_id, _ = js.Get("log_id").Int()
	words_result, _ := js.Get("words_result").Array() //"words_result": [ {"words": " TSINGTAO"}, {"words": "青島睥酒"} ] }
	tmp := words_result[0].(map[string]interface{})
	word = tmp["words"].(string)
	word = strings.Replace(word, " ", "", -1)
	Info("word", word) //对于interface{}，print只会打印其内存地址，所以要.(string)

	return
}
